from flask_restful import Api, marshal, Resource, reqparse
from flask import Blueprint, Response, jsonify
from models import UserModel, db
import redis
import random
user_bp = Blueprint('user_bp', __name__)
api = Api(user_bp)


class LoginView(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username')
        parser.add_argument('password')
        parser.add_argument('mobile')
        parser.add_argument('code')
        args = parser.parse_args()
        account = args.get('username')
        password = args.get('password')
        mobile = args.get('mobile')
        code = args.get('code')
        print('账号：%s>>密码%s>>手机号%s'%(account, password, mobile))
        try:
            user = UserModel.query.filter_by(mobile=mobile).first()
            users = UserModel(
                account=account,
                password=password,
                mobile=mobile,
            )
            db.session.add(users)
            db.session.commit()
            res = redis.Redis()
            sms = res.get(mobile)
            print('验证码:', sms)
            if sms.decode('utf-8') == code:
                return jsonify(code=200, msg='登陆成功')
            else:
                return jsonify(code=400, msg='登陆失败')
        except Exception as e:
            userse = UserModel.query.filter_by(mobile=mobile).update({
                'account':account, 'password':password
            })
            db.session.commit()
            res = redis.Redis()
            sms = res.get(mobile)
            print('验证码:', sms)
            if sms.decode('utf-8') == code:
                return jsonify(code=200, msg='登陆成功')
            else:
                return jsonify(code=400, msg='登陆失败')


api.add_resource(LoginView, '/users/login')


class Sms_code(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('mobile')
        args = parser.parse_args()
        mobile = args.get('mobile')
        res = redis.Redis()
        sms = res.get(mobile)
        if sms:
            print('验证码', sms)
            return jsonify(code=400, msg='请不要频发注册验证码')
        else:
            data = random.randint(1000, 9999)
            res.set(mobile, data, ex=20)
            print('验证码', data)
            return jsonify(code=200, msg='已发送', sms=data)


api.add_resource(Sms_code, '/users/sms_code')

